package com.example.framework.mq.rocketmq.core.util;

import com.example.framework.common.util.MsgPackUtils;
import com.example.framework.common.util.json.JsonUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RocketMQProducerUtils {

    private static DefaultMQProducer producer;

    @Autowired
    public void setProducer(DefaultMQProducer producer) {
        RocketMQProducerUtils.producer = producer;
    }

    @SneakyThrows
    public static SendResult sendMessage(String topic, String tag, Object msgBody) {
        log.info("准备发送RocketMQ消息，topic={}, tag={}, msg={}", topic, tag, msgBody instanceof String ? msgBody : JsonUtils.toJsonString(msgBody));
        // 创建消息，并指定Topic，Tag和消息体
        Message msg = new Message(topic, tag, MsgPackUtils.serialize(msgBody));
        // 发送消息到一个Broker
        SendResult sendResult = producer.send(msg);
        // 通过sendResult返回消息是否成功送达
        log.info("发送RocketMQ消息结果：{}", sendResult);
        return sendResult;
    }

    @SneakyThrows
    public static void sendMessageAsync(String topic, String tag, Object msgBody) {
        log.info("准备发送异步RocketMQ消息，topic={}, tag={}, msg={}", topic, tag, msgBody instanceof String ? msgBody : JsonUtils.toJsonString(msgBody));
        // 创建消息，并指定Topic，Tag和消息体
        Message msg = new Message(topic, tag, MsgPackUtils.serialize(msgBody));
        // 发送消息到一个Broker
        producer.send(msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("发送RocketMQ消息成功：{}", sendResult);
            }

            @Override
            public void onException(Throwable e) {
                log.error("发送RocketMQ消息失败：e={}", e.getMessage());
            }
        });
    }

}
